#include "functions.h"

void next_interval(struct timeval *next_time, const struct timeval *current_time, long interval)
{
	/* MAX_MICRO_SEC = 1000000, define in function.h */
	if(current_time->tv_usec + interval > MAX_MICRO_SEC)
	{
		next_time->tv_sec = current_time->tv_sec + 1;
		next_time->tv_usec = (current_time->tv_usec + interval) % MAX_MICRO_SEC;
	}
	else
	{
		next_time->tv_sec = current_time->tv_sec;
		next_time->tv_usec = current_time->tv_usec + interval;
	}
}

int timeval_comparison(const struct timeval *time_1, const struct timeval *time_2)
{
	int return_value = 0;

	if(time_1->tv_sec > time_2->tv_sec)
		return_value = 1;
	else if(time_1->tv_sec < time_2->tv_sec)
		return_value = 2;

	if(!return_value)
	{
		if(time_1->tv_usec > time_2->tv_usec)
			return_value = 1;
		else if(time_1->tv_usec < time_2->tv_usec)
			return_value = 2;
	}

	return return_value;
}

void interval_definition(struct timeval **interval_array, const struct timeval *start_time, long interval, int number_of_tests)
{
	int i;

	interval_array[0] = malloc(sizeof(struct timeval));
	interval_array[0]->tv_sec = start_time->tv_sec;
	interval_array[0]->tv_usec = start_time->tv_usec;

	for(i = 1; i < number_of_tests; i++)
	{
		interval_array[i] = malloc(sizeof(struct timeval));
		next_interval(interval_array[i], interval_array[i-1], interval); 
	}
}

int active_launch(long interval, int number_of_tests)
{
	struct timeval start_time;
	struct timeval **interval_array = malloc(sizeof(struct timeval*)*number_of_tests);
	struct timeval current_time;
	int i = number_of_tests;

	if(!gettimeofday(&start_time, NULL))
	{
		interval_definition(interval_array, &start_time, interval, number_of_tests);

		while(i)
		{
			if(!gettimeofday(&current_time, NULL))
			{
				if(timeval_comparison(interval_array[number_of_tests-i], &current_time) != 1)
				{
					printf("next_interval : %ld sec, %ld micro sec\n", interval_array[number_of_tests-i]->tv_sec, interval_array[number_of_tests-i]->tv_usec);
					printf("\tcurrent_time : %ld sec, %ld micro sec\n", current_time.tv_sec, current_time.tv_usec);
					i--;
				}
			}
			else
			{
				perror("Error while getting the current time\n");
				exit(0);
			}
		}
	}
	else
	{
			perror("Error while getting the start time\n");
			exit(0);
	}

	clean_interval_array(interval_array, number_of_tests);
	return 1;
}

void clean_interval_array(struct timeval **interval_array, int number_of_tests)
{
	int i;

	for(i = 0; i < number_of_tests; i++)
		free(interval_array[i]);

	free(interval_array);
}